﻿using System;
using System.IO;
using wojilu.Members.Users.Domain;
using wojilu.Members.Users.Interface;
using wojilu.Members.Users.Service;
using wojilu.Web.Controller.Helper;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller
{
    public class InstallerController : ControllerBase
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(InstallerController));

        public virtual IUserService userService { get; set; }

        private static readonly Random rd = new Random();

        public InstallerController()
        {
            userService = new UserService();
        }

        [HttpGet]
        public void Index()
        {
            // 检测网站目录权限
            testDiskPermission();

            setUserAndApp();

            echoAjaxOk();
            ctx.web.Redirect("/admin/");
        }

        public virtual void setUserAndApp()
        {
            // 1）初始化网站基本信息
            SiteInitHelper initHelper = ObjectContext.Create<SiteInitHelper>();
            if (initHelper.HasInit() == false)
            {
                initHelper.InitSite();
            }

            // 2）创建用户
            User user = new User();
            user.Name = "admin";
            user.Pwd = "0760wcn";
            user.Email = "100538511@qq.com";
            user.isclass = 1;
            user.inputclassid = 1;
            user.isremote = 1;
            user.RealName = "admin";

            user = userService.Register(user, ctx);
            if (ctx.HasErrors)
            {
                echoText(errors.ErrorsText);
                return;
            }

            // 设置安装完毕
            updateSiteDone();

            // 重启网站
            sys.Clear.ClearAll();
        }

        private static void updateSiteDone()
        {
            config.Instance.Site.IsInstall = true;
            config.Instance.Site.Update("IsInstall", true);
        }

        // 在检测之前，必须关闭log，将其设为error，否则日志系统会提前写磁盘，然后提前报错
        private void testDiskPermission()
        {
            testRootPath();
            testFrameworkPath();
            testUploadPath();
        }

        // 根目录检测
        private void testRootPath()
        {
            String fileName = getRandomFileName();
            String rootPathFile = PathHelper.Map(strUtil.Join(SystemInfo.ApplicationPath, fileName));
            writeFilePrivate(rootPathFile);

            String rootDir = PathHelper.Map(strUtil.Join(SystemInfo.ApplicationPath, "_dirtest"));
            try
            {
                Directory.CreateDirectory(rootDir);
                Directory.Delete(rootDir);
            }
            catch (Exception)
            {
                errors.Add("不能在根目录创建子目录");
            }
        }

        // framework目录检测
        private void testFrameworkPath()
        {
            String fileName = getRandomFileName();
            String filePath = strUtil.Join(cfgHelper.FrameworkRoot, fileName);
            String dataPath = PathHelper.Map(filePath);
            writeFilePrivate(dataPath);

            testConfigFile("orm.config");
            testConfigFile("route.config");
            testConfigFile("site.config");
        }

        private void testConfigFile(String configFile)
        {
            String ormPath = strUtil.Join(cfgHelper.ConfigRoot, configFile);
            ormPath = PathHelper.Map(ormPath);
            String ormContent = file.Read(ormPath);
            try
            {
                file.Write(ormPath, ormContent);
                logger.Info("write " + ormPath + " ok");
            }
            catch (Exception)
            {
                logger.Error("write error:" + configFile);
                errors.Add("出错了！这个文件不能修改: " + ormPath);
            }
        }

        // upload目录检测
        private void testUploadPath()
        {
            String fileName = getRandomFileName();
            String filePath = strUtil.Join("/upfile", fileName);
            String dataPath = PathHelper.Map(filePath);
            writeFilePrivate(dataPath);

            try
            {
                String testDir = PathHelper.Map(strUtil.Join("/upfile", "imageTest"));
                Directory.CreateDirectory(testDir);
                Directory.Delete(testDir);
            }
            catch (Exception)
            {
                errors.Add("不能在上传目录创建子目录:" + "/upfile");
            }
        }

        //-----------------------------------------------------------------------------------------

        // 创建一个文件，然后删除
        private void writeFilePrivate(String filePath)
        {
            try
            {
                file.Write(filePath, "_test_write_file_content ...");
                file.Delete(filePath);
                logger.Info("write test ok:" + filePath);
            }
            catch (IOException ex)
            {
                errors.Add(ex.Message);
                logger.Error("write error:" + filePath);
            }
        }

        private String getRandomFileName()
        {
            String fileName = "_test_write_file_" + Guid.NewGuid() + ".txt";
            return fileName;
        }

    }
}
